<template>
  <div class="form-single-fragment" style="position: relative">
    <router-header title="合同审核"></router-header>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      size="mini"
      :disabled="true"
      label-position="right"
    >
      <el-row :gutter="20" class="form-single-info">
        <el-col :span="20">
          <el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="合同名称" prop="contractName">
                  <el-input
                    class="input-item"
                    v-model="ruleForm.contractName"
                    placeholder="请输入"
                    maxlength="20"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业名称" prop="enterpriseName">
                  <el-input
                    class="input-item"
                    v-model="ruleForm.enterpriseName"
                    placeholder="请输入"
                    maxlength="20"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同编号" prop="contractCode">
                  <el-input
                    class="input-item"
                    v-model="ruleForm.contractCode"
                    disabled
                    placeholder="请输入"
                    maxlength="20"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业属性" prop="enterpriseAttribute">
                  <el-select
                    v-model="ruleForm.enterpriseAttribute"
                    placeholder="请选择"
                  >
                    <el-option label="国有企业" value="国有企业"></el-option>
                    <el-option label="国有控股" value="国有控股"></el-option>
                    <el-option label="外资企业" value="外资企业"></el-option>
                    <el-option label="合资企业" value="合资企业"></el-option>
                    <el-option label="私营企业" value="私营企业"></el-option>
                    <el-option label="事业单位" value="事业单位"></el-option>
                    <el-option
                      label="国家行政机关"
                      value="国家行政机关"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业联系人" prop="contactPerson">
                  <el-input
                    class="input-item"
                    v-model="ruleForm.contactPerson"
                    placeholder="请输入"
                    maxlength="8"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业联系电话" prop="telephone">
                  <el-input
                    class="input-item"
                    v-model="ruleForm.telephone"
                    placeholder="请输入"
                    maxlength="11"
                    type="tel"
                    onkeyup="value=value.replace(/[^\d]/g,'')"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属地区" prop="districtCode">
                  <el-cascader
                    v-model="ruleForm.districtCode"
                    ref="ref_areaCodes"
                    :options="areaCodelist"
                    :props="areaCodeprops"
                    clearable
                    @change="areaCodesChange"
                  ></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="详细地址" prop="detailedAddress">
                  <el-input
                    class="input-item"
                    v-model="ruleForm.detailedAddress"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="签约时间" prop="signingDate">
                  <el-date-picker
                    v-model="ruleForm.signingDate"
                    type="date"
                    placeholder="选择日期"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="业务类型" prop="businessType">
                  <el-cascader
                    v-model="businessType"
                    ref="ref_business"
                    :options="businesstypeTree"
                    :props="businesstProps"
                    :show-all-levels="false"
                    clearable
                    @change="handleChangeBusinessType"
                  ></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同金额" prop="contractAmount">
                  <el-input
                    type="number"
                    class="input-item"
                    v-model="ruleForm.contractAmount"
                    placeholder="请输入"
                    maxlength="20"
                    oninput="if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}if(value<0){value='0'}"
                  >
                    <el-select v-model="ruleForm.units" slot="append" placeholder="请选择" style="width: 130px; padding: 0px 25px; margin: -5px -55px;">
                      <el-option
                        v-for="item in unitsList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.label">
                      </el-option>
                    </el-select>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="是否需要会审："
                  label-width="180px"
                  prop="reviewStatus"
                >
                  <el-radio-group v-model="ruleForm.reviewStatus">
                    <el-radio :label="0">否</el-radio>
                    <el-radio :label="1">是</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同附件" prop="accessory">
                  <Upload v-model="ruleForm.accessory" fielState="2" :id="ruleForm.id" readonly></Upload>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remarks">
                  <el-input
                    type="textarea"
                    rows="4"
                    class="input-item"
                    v-model="ruleForm.remarks"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-row>
          <el-col
            :span="24"
            style="font-size: 16px; font-weight: bold; margin-bottom: 15px"
            >{{ ruleForm.reviewStatus === 1 ? "会审流程" : "审批流程" }}</el-col
          >
          <el-col :span="24">
            <el-form-item
              :label="ruleForm.reviewStatus === 1 ? '会审流程：' : '审批流程：'"
              prop="approver"
            >
              <template v-if="isArchive">
                <!-- 归档 -->
                <Approver
                  v-if="
                    archiveData.archiveApprovaers &&
                    archiveData.archiveApprovaers.length
                  "
                  :readonly="true"
                  :approverList="archiveData.archiveApprovaers"
                ></Approver>
              </template>
              <template v-else>
                <!-- 会审或盖章 -->
                <Approver
                  v-if="ruleForm.approver && ruleForm.approver.length"
                  :readonly="true"
                  :approverList="ruleForm.approver"
                ></Approver>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="抄  送：" prop="csr">
              <template v-if="isArchive">
                <!-- 归档 -->
                <Approver
                  v-if="archiveData.ccArr && archiveData.ccArr.length"
                  :isCc="true"
                  :readonly="true"
                  :approverList="archiveData.ccArr"
                ></Approver>
              </template>
              <template v-else>
                <!-- 会审或盖章 -->
                <Approver
                  v-if="ruleForm.csrArr && ruleForm.csrArr.length"
                  :isCc="true"
                  :readonly="true"
                  :approverList="ruleForm.csrArr"
                ></Approver>
              </template>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="examineForm"
      label-width="120px"
      size="mini"
      label-position="right"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="审批意见" prop="opinion">
            <el-input
              type="textarea"
              rows="4"
              class="input-item"
              v-model="ruleForm.opinion"
              placeholder="请输入审批意见"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item style="padding: 20px 0">
            <el-button @click="confirm('2')">驳回</el-button>
            <el-button type="primary" @click="confirm('1')">通过</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import headerImgSrc from '@/assets/img/default-header.png'
import { Businesstype } from '@/api/business.js';
import { Contracts, fileUploadFileDo } from '@/api/projectAdministration.js';
import { SystemController } from '@/api';
import { EcologicalkKnowledge } from '@/api/knowledgeBases.js';
import Upload from './components/Upload.vue';
import UserListDialog from './components/userListDialog.vue';
import Approver from './components/approver.vue';
import { getType } from '@/utils';
export default {
  name: 'Winasingle',
  filters: {
    approverFilter (val) {
      const data = {
        0: '一',
        1: '二',
        2: '三',
        3: '四',
        4: '五',
        5: '六',
        6: '七',
        7: '八',
        8: '九',
        9: '十',
        10: '十一',
        11: '十二',
        12: '十三',
        13: '十四',
        14: '十五',
        15: '十六',
        16: '十七',
        17: '十八',
        18: '十九',
        19: '二十',
        20: '二十一',
        21: '二十二',
        22: '二十三',
        23: '二十四',
        24: '二十五',
        25: '二十六',
        26: '二十七',
        27: '二十八',
        28: '二十九',
        29: '三十'
      };
      return data[val];
    }
  },
  props: {
    contractId: {
      default: undefined
    }
  },
  components: {
    Upload,
    Approver
  },
  data () {
    return {
      unitsList: [
        {value: '0', label: '元'},
        {value: '1', label: '万元'},
        {value: '2', label: '亿元'}
      ],
      headerImgSrc: headerImgSrc,
      isShowloading: false,
      action: fileUploadFileDo,
      approverDialog: false,
      fileLists: [],
      acceptStr:
        '.doc,.docx,.xls,.xlsx,.jpg,.png,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      businesstypeTree: [],
      businessType: '',
      businesstProps: {
        value: 'id',
        label: 'businessName',
        children: 'children',
        checkStrictly: true,
        emitPath: false
        // multiple: true
      },
      ruleForm: {
        contractName: '', // 合同名称
        enterpriseName: '', // 企业名称
        contractCode: '', // 合同编号
        enterpriseAttribute: '', // 企业属性
        contactPerson: '', // 企业联系人
        telephone: '', // 联系人电话
        districtCode: '', // 所属地区
        detailedAddress: '', // 详细地址
        signingDate: '', // 签约时间
        businessType: '', // 业务类型
        contractAmount: '', // 合同金额
        reviewStatus: 0, // 是否会审
        process: '', // 根据会审决定什么审批流程
        accessory: [], // 合同附件
        remarks: '', // 备注
        approver: [], // 流程人员
        csr: '', // 抄送
        opinion: '', // 意见

        contractId: '',
        projectId: '',
        units: ''
      },
      archiveData: {}, // 归档信息
      areaCodelist: [],
      areaCodeprops: {
        label: 'name',
        value: 'id',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      rules: {
        contractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
        enterpriseName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        contractCode: [{ required: false, message: '请输入合同编号', trigger: 'blur' }],
        enterpriseAttribute: [{ required: true, message: '请选择企业属性', trigger: 'change' }],
        contactPerson: [{ required: true, message: '请输入企业联系人', trigger: 'blur' }],
        telephone: [{ required: true, message: '请输入联系人电话', trigger: 'blur' }],
        districtCode: [{ required: true, message: '请选择所属地区', trigger: 'change' }],
        detailedAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
        signingDate: [{ required: true, message: '请选择签约时间', trigger: 'change' }],
        businessType: [{ required: true, message: '请选择业务类型', trigger: 'change' }],
        contractAmount: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
        reviewStatus: [{ required: true, message: '请选择是否会审', trigger: 'change' }],
        accessory: [{ required: true, message: '请上传合同附件', trigger: 'change' }],
        remarks: [{ required: false, message: '请输入备注', trigger: 'blur' }],
        approver: [{ required: false, message: '请选择流程人员', trigger: 'change' }],
        csr: [{ required: false, message: '请选择抄送人员', trigger: 'change' }],
        opinion: [{ required: true, message: '请输入审核意见', trigger: 'blur' }]
      },
      relationType: '',
      relationDialog: false,
      relationList: [],
      relationTotal: 0,
      relationQueryParmas: {
        size: 10,
        current: 1
      },
      executorLoading: false,
      executorList: [],
      executorListCount: 0
    };
  },
  created () {
    this.loadareaCodelistDict();
    this.ruleForm.units = this.unitsList[0].label
  },
  // 合同审核状态(枚举1=会审审批中 、2=会审审批通过、3=会审审批驳回、4=盖章审批中、5=盖章审批驳回、6=审批完成、7=待归档、8=归档中、9=归档驳回、10=已完成)
  computed: {
    // 是否为会审
    isCame () {
      return this.ruleForm.verifyStatus === 1 ||
        this.ruleForm.verifyStatus === 2 ||
        this.ruleForm.verifyStatus === 3
    },
    // 是否为盖章
    isSeal () {
      return this.ruleForm.verifyStatus === 4 ||
        this.ruleForm.verifyStatus === 5
    },
    // 是否为归档
    isArchive () {
      return this.ruleForm.verifyStatus === 7 ||
        this.ruleForm.verifyStatus === 8 ||
        this.ruleForm.verifyStatus === 9
    }
  },
  mounted () {
    this.loadbusinesstypeTree();
    this.remoteMethod()
    if (this.contractId) {
      this.loadContractdetail();
    }
  },
  methods: {
    // 审核按钮
    confirm (state) {
      this.rules.opinion[0].required = state === '2'
      this.$refs['examineForm'].validate((valid) => {
        if (!valid) {
          console.log('error submit!!');
          return false;
        }
        let params = {
          contractId: this.contractId,
          approvalOpinion: this.ruleForm.opinion,
          state: state
        }
        let fnName = this.isArchive ? 'contractThroughArchive' : 'throughContract';
        Contracts[fnName](this, params).then(res => {
          this.$message.success('操作成功！');
          this.ruleForm.opinion = ''
          this.resetForm();
        })
      });
    },
    // 选择审批人员
    selectApprover () {
      this.$dialog.show('选择审批人员', UserListDialog, {
        area: ['700px', '70vh']
      }, {
        userList: this.executorList,
        count: this.executorListCount
      }).then(res => {
        this.ruleForm.approver.push(res);
        console.log('选择之后', this.ruleForm.approver);
      }).catch(e => {
      });
    },
    // 选择抄送人员
    selectCsr () {
      this.$dialog.show('选择抄送人员', UserListDialog, {
        area: ['700px', '70vh']
      }, {
        userList: this.executorList,
        count: this.executorListCount
      }).then(res => {
        this.ruleForm.csr.push(res.userId);
      }).catch(e => {
      });
    },
    // 任务执行人搜索
    remoteMethod (query) {
      this.executorLoading = true;
      SystemController.getUserList(this, {
        orderParam: [{ asc: false, fieldName: 'loginName' }],
        pageParam: {
          pageNum: 1,
          pageSize: 10
        },
        sysUserDtoFilter: { loginName: query }
      })
        .then((res) => {
          this.executorList = res.data.dataList;
          this.executorListCount = res.data.totalCount;
          this.executorLoading = false;
        })
        .catch((e) => {
          this.executorLoading = false;
        });
    },
    // 审批人删除
    handleDelOpportunitiesApprover (index) {
      this.ruleForm.approver.splice(index, 1)
    },
    handleChangeBusinessType (val) {
      this.ruleForm.businessType = val;
      if (val) {
        this.ruleForm.businessTypeName = this.$refs.ref_business.getCheckedNodes()[0]?.pathNodes[0]?.label
      }
    },
    // 关联信息
    handleClickRelation (type) {
      this.relationType = type;
      if (this.relationType === 'business') {
        this.getOpportunities();
      } else {
        this.getProject()
      }
      this.relationDialog = true;
    },
    handleChooseRelation (row) {
      console.log(row);
      // 商机名称/项目名称
      this.ruleForm.contractName = this.relationType === 'business' ? row.oppoName : row.projectName;
      // 企业名称
      this.ruleForm.enterpriseName = this.relationType === 'business' ? row.custName : row.customerName;
      // 企业联系人
      this.ruleForm.contactPerson = row.contacts;
      // 联系电话
      this.ruleForm.telephone = row.telephone;
      // 企业属性
      this.ruleForm.enterpriseAttribute = row.contactProperty;
      // 商机地区
      this.ruleForm.districtCode = Number(this.relationType === 'business' ? row.oppoDistrictCode : row.areaId);
      // 详细地址
      this.ruleForm.detailedAddress = row.detailedAddress;
      // 业务类型
      this.businessType = row.businessType;
      this.ruleForm.businessType = row.businessType;
      if (this.relationType === 'business') { // 商机
        // id
        this.ruleForm.opportunityId = row.id;
        // 编码
        this.ruleForm.contractCode = row.oppoCode;
      } else { // 项目
        // id
        this.ruleForm.projectIdStr = row.id;
        // 编码
        this.ruleForm.contractCode = row.projectCode;
      }
      this.relationDialog = false;
    },
    getOpportunities () {
      this.relationQueryParmas.allOppo = 100
      Contracts.queryBusiness(this, this.relationQueryParmas)
        .then((res) => {
          this.relationList = res.data.data.records;
          this.relationTotal = res.data.data.total;
        })
        .catch((e) => { });
    },
    getProject () {
      let params = {
        ...this.relationQueryParmas,
        projectBinding: 0
      }
      Contracts.queryProject(this, params)
        .then((res) => {
          this.relationList = res.data.data.records;
          this.relationTotal = res.data.data.total;
        })
        .catch((e) => { });
    },
    handleRelationSizeChange (val) {
      this.relationQueryParmas.size = val;
      if (this.relationType === 'business') {
        this.getOpportunities();
      } else {
        this.getProject();
      }
    },
    handleRelationCurrentChange (val) {
      this.relationQueryParmas.current = val;
      if (this.relationType === 'business') {
        this.getOpportunities();
      } else {
        this.getProject();
      }
    },
    areaCodesChange () {
      this.$refs['ref_areaCodes'].dropDownVisible = false;
    },
    /**
     * 合同详情
     */
    loadContractdetail () {
      let params = {
        id: this.contractId
      };
      return new Promise((resolve, reject) => {
        Contracts.detail(this, params)
          .then((res) => {
            let data = res.data;
            data.contractVo.accessory = JSON.parse(data.contractVo.accessory);
            data.contractVo.csrArr = data.contractVo.ccpeopleVos?.map(v => {
              v.showName = v.userName;
              return v;
            })
            this.ruleForm = data.contractVo;
            this.businessType = data.contractVo.businessType;
            this.ruleForm.stageNumber = [];
            let accessory = this.ruleForm?.accessory;
            this.ruleForm.accessory = getType(accessory).isString ? JSON.parse(accessory) : accessory;
            // 归档相关
            if (this.isArchive && data.contractArchive) {
              data.contractArchive.ccArr = data.contractArchive?.ccPeopleName?.split(',').map(v => {
                return {
                  'showName': v
                }
              });
              console.log('抄送列表', data.contractArchive?.ccPeopleName);
              this.archiveData = data.contractArchive;
            }
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    /**
     * 业务类型信息表树形列表
     */
    loadbusinesstypeTree () {
      return new Promise((resolve, reject) => {
        Businesstype.tree(this)
          .then((res) => {
            if (res.success) {
              this.businesstypeTree = res.data;
            }
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    /**
     * 行政区划
     */
    loadareaCodelistDict () {
      return new Promise((resolve, reject) => {
        EcologicalkKnowledge.listDict(this)
          .then((res) => {
            let areaCodelist = res.data;
            let areaCodelistnew = [];
            areaCodelist.forEach((item, index) => {
              if (!item.parentId) {
                item.children = [];
                areaCodelistnew.push(item);
              }
            });
            areaCodelistnew.forEach((item1, index1) => {
              let info = areaCodelist.find((item2, index2) => {
                return item1.id === item2.parentId;
              });
              if (info) {
                item1.children = [];
                areaCodelist.forEach((item3, index3) => {
                  if (item1.id === item3.parentId) {
                    item1.children.push(item3);
                  }
                });
              } else {
                item1.children = null;
              }
            });
            areaCodelistnew.forEach((item4, index4) => {
              if (item4.children) {
                item4.children.forEach((item5, index5) => {
                  let info2 = areaCodelist.find((item6, index6) => {
                    return item5.id === item6.parentId;
                  });
                  if (info2) {
                    item5.children = [];
                    areaCodelist.forEach((item7, index7) => {
                      if (item5.id === item7.parentId) {
                        item5.children.push(item7);
                      }
                    });
                  } else {
                    item5.children = null;
                  }
                });
              }
            });
            this.areaCodelist = areaCodelistnew;
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    /**
     * 上传文件-成功
     */
    handleSuccess (file, fileList) {
      this.fileLists = fileList;
    },
    /**
     * 上传文件-删除
     */
    handleRemove (file, fileList) {
      this.fileLists = fileList;
    },
    /**
     * 上传图片限制条件
     */
    beforeAvatarUpload (file, fileList) { },
    /**
     * 提交表单
     */
    submitForm () {
      console.log(this.ruleForm);
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.isShowloading = true;
          if (this.ruleForm.id) {
            Contracts.update(this, { updateDto: this.ruleForm }).then((res) => {
              this.isShowloading = false;
              this.resetForm();
            });
          } else {
            Contracts.add(this, { addDto: this.ruleForm }).then((res) => {
              this.isShowloading = false;
              this.resetForm();
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm () {
      this.$router.go(-1);
    }
  }
};
</script>

<style lang="scss" scoped>
.approver-inquiry {
  display: flex;
  padding: 0 10px;
  line-height: 28px;
  height: 28px;
  justify-content: space-between;
  margin-bottom: 20px;
}
.approver {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  .approver-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .approver-item-con {
      padding: 0px 10px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      .approver-item-c {
        margin: 10px 0;
        text-align: center;
      }
    }
  }
  // /deep/.el-tag {
  //   width: 100%;
  //   position: relative;
  // }
  // /deep/.el-tag--medium .el-icon-close {
  //   transform: scale(0.8) translateY(-50%);
  // }
  // /deep/.el-tag .el-icon-close {
  //   position: absolute;
  //   top: 50%;
  //   right: 5px;
  //   transform: translateY(-50%);
  // }
}
h4 {
  margin-bottom: 0;
}
.table_container {
  margin: 10px 0;
}
.form-single-info {
  display: flex;
  justify-content: center;
}
.el-form-info {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
}
.el-form-info strong {
  margin: 0 10px;
}
.table_input /deep/.el-form-item__content {
  margin-left: 0 !important;
}
.table_input.el-form-item {
  margin: 12px 0;
}
/deep/.el-table {
  margin: 0 0 0 10px;
  width: calc(100% - 10px);
}
/deep/.el-upload-list {
  width: 40%;
}
.el-col-12 {
  height: 48px;
}
/* .el-col {
  min-height: 47px;
} */
</style>
